package com.genymobile.scrcpy.five.connection;

import com.genymobile.scrcpy.five.LogUtils;

import fi.iki.elonen.NanoHTTPD;

import java.util.List;
import java.util.Map;
import java.util.Objects;

public class HttpServer extends NanoHTTPD {
    private static final String TAG = HttpServer.class.getSimpleName();

    private final ConnectionServer.ICallback mCallback;
    public HttpServer(int port, ConnectionServer.ICallback callback) {
        super(port);
        mCallback = callback;
        LogUtils.log(TAG, "命令的HTTP服务器已启动! " +port);
    }

    // HTTP 请求处理
    @Override
    public Response serve(IHTTPSession session) {
        String cmd = "没有参数";

        // 使用 getParameters() 代替 getParms()
        Map<String, List<String>> params = session.getParameters();
        if (params.containsKey("cmd") && !Objects.requireNonNull(params.get("cmd")).isEmpty()) {
            cmd = Objects.requireNonNull(params.get("cmd")).get(0); // 取第一个值
        }

        String result = runCmd(cmd);
        return newFixedLengthResponse(result);
    }

    // 自定义逻辑
    public String runCmd(String cmd) {
        mCallback.handleLine(cmd);
        return "Server 执行了: " + cmd;
    }
}
